package com.heima.mvplibrary.base;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.gms.maps.SupportMapFragment;
import com.heima.mvplibrary.R;
import com.heima.mvplibrary.dailog.LoadingDailog;
import com.heima.mvplibrary.iml.IViewBase;
import com.heima.mvplibrary.mvp.IView;
import com.heima.mvplibrary.utils.KnifeKit;
import com.heima.mvplibrary.utils.StaticUtils;

import java.lang.reflect.ParameterizedType;

import butterknife.Unbinder;

public abstract class BaseFragment<P extends BasePresenter> extends SupportMapFragment implements IViewBase, IView, View.OnClickListener {

    private P p;
    private View emptyView;
    private View rootView;
    Unbinder unbinder;
    private Bundle bundle;

    private LoadingDailog mProgressDialog;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        bundle = savedInstanceState;
        getLayoutId();
        initData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null && getLayoutId() > 0) {
            rootView = inflater.inflate(getLayoutId(), null);
            bindUI(rootView);
        } else {
            ViewGroup viewGroup = (ViewGroup) rootView.getParent();
            if (viewGroup != null) {
                viewGroup.removeView(rootView);
            }
        }
        return rootView;
    }



    @Override
    public void bindUI(View rootView) {
        unbinder = KnifeKit.bind(this, rootView);
    }

    /**
     * 初始化Listener
     */
    protected abstract void widgetClick(View view);

    @Override
    public void onClick(View v) {
        if (fastClick())
            widgetClick(v);

    }

    public Bundle getBundle() {
        return bundle;
    }

    /**
     * [防止快速点击]
     *
     * @return
     */
    private boolean fastClick() {
        long lastClick = 0;
        if (System.currentTimeMillis() - lastClick <= 1000) {
            return false;
        }
        lastClick = System.currentTimeMillis();
        return true;
    }

    /**
     * @param clazz 启动activity
     */
    public void start(@NonNull Class<? extends AppCompatActivity> clazz) {
        Intent intent = new Intent(getActivity(), clazz);
        startActivity(intent);
    }

    public P getP() {
        if (p == null) {
            //实例化P层，类似于p = new P();
            ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
            Class<P> clazz = (Class<P>) parameterizedType.getActualTypeArguments()[0];
            try {
                p = clazz.newInstance();
            } catch (Exception e) {
                StaticUtils.loge(e.getMessage());
            }
        }
        if (p != null) {
            if (!p.isAttachedV()) {
                p.attachView(this);
            }
        }
        return p;
    }

    public void onError(Throwable e) {
        showToast(StaticUtils.getErrorMsg(e));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (getP() != null) {
            getP().detachView();
        }
        p = null;
    }


    public void showToast(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    public void showLongToast(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 页面空布局显示
     *
     * @param isLoad 是否是加载中
     */
    public void setEmptyView(RelativeLayout layout, LinearLayout linearLayout, boolean isLoad) {
        linearLayout.removeAllViews();
        if (emptyView == null) {
            emptyView = getLayoutInflater().inflate(R.layout.view_empty, null);
        }
        layout.setVisibility(isLoad ? View.GONE : View.VISIBLE);
        linearLayout.setVisibility(isLoad ? View.VISIBLE : View.GONE);//当isload为true则显示空布局页面
        emptyView.findViewById(R.id.imageView_img).setVisibility(isLoad ? View.VISIBLE : View.VISIBLE);
        emptyView.findViewById(R.id.progressBar_loading).setVisibility(isLoad ? View.GONE : View.GONE);
        linearLayout.addView(emptyView);

    }

    /**
     * 设置适配器的空布局
     *
     * @param adapter  适配器
     * @param msg      空布局文字提示
     * @param imgResId 空布局图片资源，若isLoad为true则不生效
     * @param isLoad   是否是加载中
     */
    public void setAdapterEmptyView(BaseQuickAdapter adapter, String msg, int imgResId, boolean isLoad) {
        if (emptyView == null) {
            emptyView = getLayoutInflater().inflate(R.layout.view_empty, null);
        }
        ((TextView) emptyView.findViewById(R.id.textView_msg)).setText(msg);
        if (isLoad) {
            emptyView.findViewById(R.id.imageView_img).setVisibility(View.GONE);
            emptyView.findViewById(R.id.progressBar_loading).setVisibility(View.VISIBLE);
        } else {
            ((ImageView) emptyView.findViewById(R.id.imageView_img)).setImageResource(imgResId);
            emptyView.findViewById(R.id.imageView_img).setVisibility(View.VISIBLE);
            emptyView.findViewById(R.id.progressBar_loading).setVisibility(View.GONE);
        }
        adapter.getData().clear();
        adapter.setEmptyView(emptyView);
        adapter.notifyDataSetChanged();
    }

    /**
     * 显示错误布局
     *
     * @param adapter recyclerView的适配器
     * @param msg     错误提示信息
     */
    public void showErrorView(BaseQuickAdapter adapter, String msg) {
        //// TODO: 2019/6/5 替换错误布局图片
        setAdapterEmptyView(adapter, msg, R.drawable.loading_error, false);
    }

    /**
     * 显示空布局
     *
     * @param adapter recyclerView的适配器
     */
    public void showEmptyView(BaseQuickAdapter adapter) {
        //// TODO: 2019/6/5 替换空布局图片
        setAdapterEmptyView(adapter, "空空如也", R.drawable.loading_null, false);
    }

    /**
     * 显示加载中布局
     *
     * @param adapter recyclerView的适配器
     */
    public void showLoadView(BaseQuickAdapter adapter) {
        setAdapterEmptyView(adapter, "加载中……", 0, true);
    }



    /**
     *  控件的显示优化
     */
    public void onViewVisibility(View view,int i){
        if (view.getVisibility()==i){
            return;
        }
        view.setVisibility(i);
    }




    public void showLoadingDailog(String msg) {
        LoadingDailog.Builder loadBuilder = new LoadingDailog.Builder(getActivity());
        mProgressDialog = loadBuilder.create();
        mProgressDialog.show();
    }

    public void dismissProgress() {
        try {
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
            }
        } catch (Exception e) {
        }

    }








}